package com.item.action;

import static com.item.mobile.MobileUtil.checkParam;

import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.common.Logger;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.action.CoreController;
import com.base.dialect.PaginationSupport;
import com.base.mobile.MobException;
import com.base.util.DateUtil;
import com.base.util.FileExportUtils;
import com.base.util.ImageUtils;
import com.base.util.MyOssClient;
import com.base.util.StringUtil;
import com.item.dao.model.Admin;
import com.item.dao.model.AdminExample;
import com.item.dao.model.EssenceNew;
import com.item.dao.model.EssenceNewExample;
import com.item.dao.model.MediaFile;
import com.item.dao.model.News;
import com.item.dao.model.Note;
import com.item.dao.model.Question;
import com.item.dao.model.QuestionExample;
import com.item.dao.model.ShareSignModel;
import com.item.dao.model.SignExample;
import com.item.dao.model.User;
import com.item.exception.JSONRepUtils;
import com.item.filter.LoginFilter;
import com.item.mobile.MEnumError;
import com.item.service.AdminService;
import com.item.service.EssenceNewService;
import com.item.service.MediaFileService;
import com.item.service.NewsService;
import com.item.service.NoteAuthorService;
import com.item.service.NoteService;
import com.item.service.QuestionService;
import com.item.service.SignService;
import com.item.service.UserService;
import com.item.util.ConstantResources;
import com.item.util.JpushUtil;
import com.item.util.MyDateUtils;
import com.item.util.WebPageFileController;
import com.mdx.mobile.commons.verfy.Md5;
import com.item.dao.model.NoteShareModel;

@Controller
public class SystemController extends CoreController {
	
	private static final String BUCKET_NAME = ConstantResources.BUCKET_NAME_WEBFILE;
	
	private static Logger logger = Logger.getLogger(SystemController.class);
	
	@Autowired
	private AdminService adminService;
	
	@Autowired
	private SignService signService;
	
	@Autowired
	private QuestionService quesService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MediaFileService fileService;
	@Autowired
	private EssenceNewService newEssenceService;
	@Autowired
	private NoteService  noteService;
	@Autowired
	private NoteAuthorService authortService;
	@Autowired
	private NewsService newsService;
	//预览文件处理器
	public static WebPageFileController previewFileController = new WebPageFileController("", "preview", "utf8");
	
	/**
	 * 进入主页
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/index")
	public String index(HttpSession session, ModelMap map) throws Exception {
		Object obj = session.getAttribute(LoginFilter.SESSION_USER_KEY);
		if (obj != null) {
			return "main";
		}
		return "login";
	}
	
	
	
	@RequestMapping("/login")
	@ResponseBody
	public String login(String account, String pwd, HttpSession session) throws Exception {
		if (StringUtils.isBlank(account) || StringUtils.isBlank(pwd)) {
			return "1";
		}
		Map<String, String> map = new HashMap<String, String>();
		AdminExample example = new AdminExample();
		example.createCriteria().andAccountEqualTo(account).andPasswordEqualTo(Md5.md5(pwd)).andStateEqualTo(1);
		List<Admin> list = adminService.selectByExample(example);
		if (list != null && list.size() > 0) {
			Admin admin = list.get(0);
			map.put("id", admin.getId());
			session.setAttribute("appid", admin.getAppid());
			session.setAttribute("isM", 0);
			session.setAttribute("account", account);
			session.setAttribute(LoginFilter.SESSION_USER_KEY, map);
//			Cookie cookie = new Cookie("appid",admin.getAppid());
//			response.addCookie(cookie);
		} else {
			return "2";
		}
		return "success";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/changePwd")
	@ResponseBody
	public String changePwd(String oldpwd, String newpwd, HttpSession session) throws Exception {
		HashMap<String, String> map = (HashMap) session.getAttribute(LoginFilter.SESSION_USER_KEY);
		String id = map.get("id");
		// 超级管理员
		AdminExample example = new AdminExample();
		example.createCriteria().andIdEqualTo(id).andPasswordEqualTo(Md5.md5(oldpwd));
		List<Admin> list = adminService.selectByExample(example);
		if (list != null && list.size() > 0) {
			Admin admin = new Admin();
			admin.setId(id);
			admin.setPassword(Md5.md5(newpwd));
			admin.setModifyTime(new Date());
			adminService.updateByPrimaryKeySelective(admin);
			return "success";
		}
		return "";
	}
	
	@RequestMapping("/logoutM")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:index.do";
	}
	
	@RequestMapping("/pageContent")
	@ResponseBody
	public String pageContent(String url) throws Exception {
		WebPageFileController fileController = new WebPageFileController("ydd","news","utf-8");
		String result = fileController.read(url, "utf-8"); //为编辑修改而去掉这些
		result = result.replaceAll("(?s).*?<!--editorcontentstart-->(.*?)<!--editorcontentend-->.*", "$1");
		result = result.replaceAll("(?s)<!DOCTYPE html>.*?<body>(.*?)<script src=\"http://cdn.*", "$1");
		return result;
	}
	
	/**
	 * 预览网页文件
	 * @param contextReal
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/preview",method=RequestMethod.POST)
	@ResponseBody
	public String preview(String contextReal) throws Exception {		
		return previewFileController.write(previewFileController.getHtmlContentUTF8(contextReal), "html");
	}
	
	@RequestMapping("/showImg")
	public String showImg(){
		return "showImg";
	}
	
	@RequestMapping("/showpushJ")
	public String showPushJ() {
		return "pushJ";
	}
	
	@RequestMapping(value="/noteShare")
	@ResponseBody
	public String noteShare(String noteId)throws Exception{
		if(StringUtils.isBlank(noteId)){
			return "fail";
		}
		NoteShareModel model = new NoteShareModel();
		Note note = noteService.selectByPrimaryKey(noteId);
		if(note != null){
			model.setNote(note);
			model.setAuthor(authortService.selectByPrimaryKey(note.getAuthor()));
		}else{
			return "fail";
		}
		return JSONRepUtils.serialize(model, 0);
	}
	
	@RequestMapping(value="/teacherShare")
	@ResponseBody
	public String teacherShare(String teacherId)throws Exception{
		if(StringUtils.isBlank(teacherId)){
			return "fail";
		}
		List<EssenceNew> result = new ArrayList<EssenceNew>();
		EssenceNewExample enex = new EssenceNewExample();
		enex.createCriteria().andAuthorEqualTo(teacherId);
		enex.setOrderByClause("is_over DESC,top DESC");
		PaginationSupport.setContext(1, 10, null);
		List<EssenceNew> lists = newEssenceService.selectByExample(enex);
		for(EssenceNew item : lists){
			result.add(item);
		}
		return JSONRepUtils.serialize(lists, 0);
	}
	
	
	@RequestMapping(value="/shareSign")
	@ResponseBody
	public String shareSign(String userid, String date)throws Exception{
		 ShareSignModel model = new ShareSignModel();
		if(date == null){
			date = MyDateUtils.parseDateWithDay(new Date());
		}
		if(StringUtils.isBlank(userid)){
			throw new MobException(MEnumError.NO_RECOMMEND_ERROR);
		}
		SignExample sgex = new SignExample();
		sgex.createCriteria().andUseridEqualTo(userid).andDateLessThanOrEqualTo(DateUtil.parseDate(date, "yyyy-MM-dd"));
		model.setSignCount(signService.countByExample(sgex));
		Map<String,String> map = new HashMap<String, String>();
        map.put("userid", userid);
        map.put("date", date);
        Map<String,Long> result = quesService.getQuestionCount(map);
        model.setAddCount(result.get("todayCount").intValue());
        model.setReviewCount(result.get("reviewCount").intValue());
        model.setUserid(userid);
        //还需要userid
        User user = userService.selectByPrimaryKey(userid);
        if(user != null){
        	model.setHeadimg(StringUtil.emptyIfBlank(user.getHeadimg()));
        	model.setNickname(StringUtil.emptyIfBlank(user.getNickname()));
        }
		return JSONRepUtils.serialize(model, 0);
	}
	
	
	@RequestMapping(value="/questionPrint")
	@ResponseBody
	public String questionPrint(String userid, Integer type,String start,String end)throws Exception{
		QuestionExample qex = new QuestionExample();
		checkParam(userid, "userid");
		checkParam(start, "start");
		checkParam(end, "end");
		checkParam(type, "type");
		//专业课的话需要考虑两个type
		if(type == 4 || type  == 5){
			QuestionExample.Criteria cr1 = qex.createCriteria();
			qex.createCriteria().andUseridEqualTo(userid).andTypeEqualTo(4).andCreateTimeBetween(DateUtil.parseDate(start, "yyyy-MM-dd"), DateUtil.parseDate(end, "yyyy-MM-dd"));
			cr1.andUseridEqualTo(userid).andTypeEqualTo(5).andCreateTimeBetween(DateUtil.parseDate(start, "yyyy-MM-dd"), DateUtil.parseDate(end, "yyyy-MM-dd"));
		}else{
			qex.createCriteria().andUseridEqualTo(userid).andTypeEqualTo(type).andCreateTimeBetween(DateUtil.parseDate(start, "yyyy-MM-dd"), DateUtil.parseDate(end, "yyyy-MM-dd"));
		}
		qex.setOrderByClause("type DESC,create_time DESC");
		List<Question> ques = quesService.selectByExample(qex);
		for(Question q : ques){
			q.setDisplayName(fileService.selectByPrimaryKey(q.getImg()).getFilePath());
		}
		return JSONRepUtils.serialize(ques, 0);
	}
	
	/**
	 * 用于视频播放页面的数据获取
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/mediaFile")
	@ResponseBody
	public String getEssenceFile(String id){
		MediaFile file = fileService.selectByPrimaryKey(id);
		file.setBrowseCount(file.getBrowseCount() + 1);
		fileService.updateByPrimaryKeySelective(file);
		return JSONRepUtils.serialize(file, 0);
	}
	
	/**
	 * 推送的内容设置
	 * @param module
	 * @param ids
	 * @param device
	 * @param msg
	 * @return
	 */
	@RequestMapping("/pushWebUrl")
	@ResponseBody
	public String pushWeb(String module, String ids, String device, String msg) {
		boolean isBroad = true;
		if(StringUtils.isNotBlank(ids)) {
			for(String id : ids.split(",")) {
				String type = "";
				String appid = "ydd";
				String title = "";
				String msgStr = "";
				String pushId = "";
				String img = "";
				String source = "";
				String url = "";
				if(module.equalsIgnoreCase("news")) {
					News news = newsService.selectByPrimaryKey(id);
					url = news.getUrl();
					type = "1";
					title = news.getTitle();
					msgStr = news.getTitle();
					img = news.getImg();
					id = news.getId();
					source = news.getSource();
				}
				if(appid.contains("common")) {
					
				} else {
						if(isBroad) {
							Map<String, String> params = new HashMap<String, String>();
							params.put("type", type);
							params.put("target", String.format("%s%s?newsid=%s&_t=%s", ConstantResources.OSS_OUT_WEB_URL,url,id,String.valueOf(System.currentTimeMillis())));
							params.put("id", id);
							params.put("img",img);
							if(device.equals("all") || device.equals("ios")){
								if(JpushUtil.sendIosNotification(appid, msg, 1, params)== 1)
									return "length";
							}
							if(device.equals("all") || device.equals("android")){
								params.put("msg", msg);
								JpushUtil.sendAndroidMessage(appid, params);
							}
						} 
					} 
				}
				
			}
		return "success";
	}
	
	
	
	
	
	
	@RequestMapping("/downloadEssence")
	public void downloadFile(String id,HttpServletResponse resp,
			@RequestParam(value = "w", required = false) String w,
			@RequestParam(value = "h", required = false) String h,String type) throws Exception{
		if(id!=null){
			MediaFile item = fileService.selectByPrimaryKey(id);
			if (item == null) {
				throw new Exception("文件不存在");
			} else {
//				File filepath = new File(CoreConstants.FILE_PATH + "/"+item.getFilePath());
//				System.out.println(item.getFilePath());
				byte[] fileData = MyOssClient.getObject(item.getFilePath(), BUCKET_NAME);
				int width = 0, height = 0;
				if (w != null && w.length() > 0) {
					width = Integer.valueOf(w);
				}
				if (h != null && h.length() > 0) {
					height = Integer.valueOf(h);
				}
				
				if (width != 0 && item.getFileMinitype().startsWith("image")) {
//					// 检查目录
//					File tempDirectory= new File(CoreConstants.FILE_PATH + "/temp/");
//					if (!tempDirectory.isDirectory()) {
//						tempDirectory.mkdirs();
//					}
					
//					String tf =CoreConstants.FILE_PATH + "/temp/" +  item.getFileMd5() +"_"+ width + "x" + height + ".png";
					String tf ="temp/" +  item.getFileMd5() +"_"+ width + "x" + height + ".png";
					byte[] tempData = MyOssClient.getObject(tf, BUCKET_NAME);
					if (tempData == null) {
						InputStream bi = MyOssClient.getObjectStream(item.getFilePath(), BUCKET_NAME);
						if(bi != null) {
							BufferedImage bimg = ImageIO.read(bi);
							bi.close(); //关闭流
							if (height == 0) {
								tempData = ImageUtils.Compress(bimg, tf, width, BUCKET_NAME);
							} else {
								tempData = ImageUtils.Compress(bimg, tf, width, height, BUCKET_NAME);
							}
						}	
					}
					
					if(tempData != null) 
						fileData = tempData;
				}
				
				resp.setContentType(item.getFileMinitype() + "; charset=utf-8");
				if (fileData == null) {
					throw new Exception("文件没找到");
				}
				FileExportUtils.download(resp, item.getFileName(), item.getFileMinitype(), fileData,type);
			}
		}
	}
}
